#include "DistanceMeasurementAlgorithm.h"
#include "DistanceMeasurementResultWidget.h"
#include "DistanceMeasurementDrawerFactory.h"
#include <QLineF>
#include <QDebug>

DistanceMeasurementAlgorithm::DistanceMeasurementAlgorithm(QObject *parent) : MeasurementAlgorithmBase(parent), m_resultWidget(nullptr), m_drawerFactory(nullptr) {}

DistanceMeasurementAlgorithm::~DistanceMeasurementAlgorithm()
{
    delete m_resultWidget;
    delete m_drawerFactory;
}

QString DistanceMeasurementAlgorithm::algorithmName() const
{
    return tr("距离测量");
}

void DistanceMeasurementAlgorithm::initialize()
{
    // 创建结果显示界面
    if (!m_resultWidget) {
        m_resultWidget = new DistanceMeasurementResultWidget();
        // 连接测量完成信号到结果界面更新
        connect(this, &DistanceMeasurementAlgorithm::measurementProcessed,
                [this](const QString &imageId, const QVariantMap &result) {
                    Q_UNUSED(imageId);
                    if (m_resultWidget) {
                        m_resultWidget->updateDistanceResult(result);
                    }
                });
        // 注册算法名称和图标，用于显示按钮
        emit registerMeasurementAlgorithm(algorithmName(), ":/images/images/9.png");
    }

    // 初始化绘制器工厂
    if (!m_drawerFactory) {
        m_drawerFactory = new DistanceMeasurementDrawerFactory(this);
        
        // 连接绘制器工厂的信号
        connect(m_drawerFactory, &DistanceMeasurementDrawerFactory::horizontalDoubleLineChanged, 
                this, &DistanceMeasurementAlgorithm::onLinePositionChanged);
        connect(m_drawerFactory, &DistanceMeasurementDrawerFactory::verticalDoubleLineChanged, 
                this, &DistanceMeasurementAlgorithm::onLinePositionChanged);
    }
}

MeasurementModes DistanceMeasurementAlgorithm::getSupportedModes() const
{
    MeasurementModes modes;
    modes.setFlag(MeasurementMode::HorizontalDoubleLine);
    modes.setFlag(MeasurementMode::VerticalDoubleLine);
    return modes;
}

void DistanceMeasurementAlgorithm::startMeasurement(const QString &imageId)
{
    m_imageId = imageId;
    m_processed = true;
    if (m_resultWidget)
    {
        emit registerMeasurementResultWidget(algorithmName(), m_resultWidget);
    }
}

void DistanceMeasurementAlgorithm::endMeasurement()
{
    m_imageId.clear();
    m_drawerFactory->clearAll();
    m_processed = false;
}

QString DistanceMeasurementAlgorithm::currentImageId() const
{
    return m_imageId;
}

QVariantMap DistanceMeasurementAlgorithm::getMeasurementParameters() const
{
    return m_params;
}

void DistanceMeasurementAlgorithm::setMeasurementParameters(const QVariantMap &params)
{
    m_params = params;
    // 从参数中提取并绘制测量图形
    drawMeasurementGraphics(params);
}

void DistanceMeasurementAlgorithm::drawMeasurementGraphics(const QVariantMap &params)
{
    if (!m_drawerFactory) {
        return;
    }
    
    // 检查必要参数
    if (!params.contains("MeasurementType")) {
        qWarning() << "MeasurementType is no find";
        return;
    }
    
    // 从参数中获取图形场景
    if (params.contains("Canvas")) {
        QGraphicsScene *scene = params.value("Canvas").value<QGraphicsScene*>();
        if (scene) {
            // 设置场景给绘制器工厂
            m_drawerFactory->setScene(scene);
        }
    }
    
    // 获取测量类型并转换为MeasurementMode枚举
    QString measurementType = params.value("MeasurementType").toString();
    MeasurementMode mode = MeasurementMode::HorizontalDoubleLine; // 默认模式
    
    if (measurementType == "HorizontalDoubleLine") {
        mode = MeasurementMode::HorizontalDoubleLine;
    } else if (measurementType == "VerticalDoubleLine") {
        mode = MeasurementMode::VerticalDoubleLine;
    } else {
        qWarning() << "MeasurementMode error:" << measurementType;
        return;
    }
    
    // 获取显示图像并从中提取图像尺寸
    int imageWidth = 0;
    int imageHeight = 0;
    
    if (params.contains("DisplayImage")) {
        QImage image = params.value("DisplayImage").value<QImage>();
        if (!image.isNull()) {
            imageWidth = image.width();
            imageHeight = image.height();
        }
    }
    
    if (imageWidth <= 0 || imageHeight <= 0) {
        qWarning() << "image size error";
        return;
    }
    
    // 获取缩放比例（默认为1.0）
    double scale = 1.0;
    if (params.contains("ImageScale")) {
        scale = params.value("ImageScale").toDouble();
    }
    
    // 获取图像偏移信息
    QPointF offset(0.0, 0.0);
    if (params.contains("ImageOffset")) {
        QSize offsetSize = params.value("ImageOffset").value<QSize>();
        offset.setX(offsetSize.width());
        offset.setY(offsetSize.height());
    }
    
    // 初始化测量工具
    if (m_drawerFactory) {
        m_drawerFactory->initializeMeasurementTool(mode, imageWidth, imageHeight, scale, offset);
    }
    
}

/**
 * @brief 设置测量结果（用于撤销/重做操作）
 * @param imageId 图像唯一标识符
 * @param measurementResult 测量结果，包含距离数据
 * 
 * 该方法直接设置测量结果而不重新计算，用于撤销/重做操作时恢复之前的测量状态。
 * 它会更新内部状态、注册结果显示界面并发送测量结果信号。
 */
void DistanceMeasurementAlgorithm::setMeasurementResult(const QVariantMap &measurementResult)
{
    // 设置图像ID和测量结果
    m_processed = true;
    
    // 注册结果显示widget
    if (m_resultWidget) {
        emit registerMeasurementResultWidget(algorithmName(), m_resultWidget);
        // 更新结果显示窗口
        m_resultWidget->updateDistanceResult(measurementResult);
    }
}


void DistanceMeasurementAlgorithm::setScale(double scale)
{
    // 实现缩放比例设置
    qDebug() << "Setting scale for DistanceMeasurementAlgorithm:" << scale;
    // 保存缩放比例到参数中
    m_params["ImageScale"] = scale;
    
    // 更新绘制器的缩放比例
    if (m_drawerFactory) {
        m_drawerFactory->updateScale(scale);
    }
}

void DistanceMeasurementAlgorithm::setUnitConversionInfo(int xUnit, int yUnit,  double lengthRatio,
                                                       double timeRatio, double wavelengthRatio, 
                                                       const QString &lengthUnit, const QString &timeUnit, 
                                                       const QString &wavelengthUnit)
{
    // 构建单位转换映射，用于测量计算
    QVariantMap unitConversionMap;
    unitConversionMap["xAxisUnit"] = xUnit;
    unitConversionMap["yAxisUnit"] = yUnit;
    unitConversionMap["lengthRatio"] = lengthRatio;
    unitConversionMap["timeRatio"] = timeRatio;
    unitConversionMap["wavelengthRatio"] = wavelengthRatio;
    unitConversionMap["lengthUnit"] = lengthUnit;
    unitConversionMap["timeUnit"] = timeUnit;
    unitConversionMap["wavelengthUnit"] = wavelengthUnit;
    m_params["UnitConversion"] = unitConversionMap;
    QVariantMap tempResult=m_Result;
    onLinePositionChanged(tempResult);
}

void DistanceMeasurementAlgorithm::onLinePositionChanged(const QVariantMap &result){
    static QString units[]={"","length","time","wavelength"};
    m_Result=result;
    QVariantMap unitConversionMap= m_params["UnitConversion"].value<QVariantMap>();
    QVariantMap updatedResult;
    updatedResult.insert("measurement_mode", result["measurement_mode"]);
    QPointF point1=result["point1"].value<QPointF>();
    QPointF point2=result["point2"].value<QPointF>();
    double distanceValue=0.0;
    if(result["measurement_mode"].toInt()==2)
    {
        distanceValue=qAbs(point1.x()-point2.x());
        QString xUintName=units[unitConversionMap.value("xAxisUnit").toInt()];
        if(xUintName.isEmpty())
        {
            updatedResult.insert("distance",distanceValue);
            updatedResult.insert("distance_unit","px");
        }
        else
        {
            distanceValue*=unitConversionMap.value(QString("%1Ratio").arg(xUintName)).toDouble();
            updatedResult.insert("distance",distanceValue);
            updatedResult.insert("distance_unit",unitConversionMap.value(QString("%1Unit").arg(xUintName)));
        }
        updatedResult.insert("start", qMin(point1.x(),point2.x()));
        updatedResult.insert("end", qMax(point1.x(),point2.x()));

    }
    else if(result["measurement_mode"].toInt()==8)
    {
        distanceValue=qAbs(point1.y()-point2.y());
        QString yUintName=units[unitConversionMap.value("yAxisUnit").toInt()];
        if(yUintName.isEmpty())
        {
            updatedResult.insert("distance",distanceValue);
            updatedResult.insert("distance_unit","px");
        }
        else
        {
            distanceValue*=unitConversionMap.value(QString("%1Ratio").arg(yUintName)).toDouble();
            updatedResult.insert("distance",distanceValue);
            updatedResult.insert("distance_unit",unitConversionMap.value(QString("%1Unit").arg(yUintName)));
        }
        updatedResult.insert("start", qMin(point1.y(),point2.y()));
        updatedResult.insert("end", qMax(point1.y(),point2.y()));
    }
    else
    {
        qDebug()<<"measurement mode error";
        return;
    }
    // 当线位置变化时，更新测量结果
    emit measurementProcessed(m_imageId, updatedResult);
}

